<template>
  <div class="out-nav">
    <el-button type="warning" icon="Setting" @click="change()">分配权限</el-button>
    <teleport to="body">
      <el-dialog v-model="isShow" title="分配权限" width="40%">
        <el-tree :data="data" :props="rule" show-checkbox node-key="id" :height="208"
          :default-checked-keys="defaultExpandedKeys" ref="treeV2" />
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="onsubmit()"> 提交 </el-button>
            <el-button @click="closeDialog()">取消</el-button>
          </span>
        </template>
      </el-dialog>
    </teleport>
  </div>
</template>

<script setup>
import { defineProps, reactive, ref } from "vue";
import { setUserrole, getAllList } from "@/api/roleList";
import { ElMessage, ElMessageBox } from "element-plus";
const props = defineProps({
  getList: {
    type: Function,
  },
  scope: {
    type: Object,
    default: function () { },
  },
});
let isShow = ref(false);
let data = reactive([]);
let treeV2 = ref(null);
const closeDialog = () => {
  isShow.value = false;
};
let defaultExpandedKeys = reactive([]);


const createExpandedKeys = (scope) => {
  scope.forEach((element) => {
    if (element.children && element.children.length) {
      createExpandedKeys(element.children);
    } else {
      if (defaultExpandedKeys.indexOf(element.id) == -1) {
        defaultExpandedKeys.push(element.id);
      }
    }
  });
};
const change = async () => {

  let res = await getAllList("tree");
  data.splice(0);
  data.push(...res.data);
  defaultExpandedKeys.splice(0);
  createExpandedKeys(props.scope.row.children);
  isShow.value = true;
}
const rule = {
  value: "id",
  label: "authName",
  children: "children",
};
const onsubmit = async () => {
  let list = treeV2.value.getCheckedKeys(false);
  let res = await setUserrole(props.scope.row.id, String(list));
  ElMessageBox.alert(res.meta.msg, "", {
    // if you want to disable its autofocus
    // autofocus: false,
    confirmButtonText: "确认",
    callback: () => {
      let ls = res.meta.status >= 200 && res.meta.status < 300;
      ElMessage({
        type: ls ? "success" : "error",
        message: ls ? "修改成功" : "修改失败",
      });
    },
  });
  closeDialog();
  props.getList();
};
</script>

<style lang="scss" scoped>
.out-nav {
  display: inline-block;
  margin: 0 10px;
}
</style>